package pts

import (
	"time"
)

type HttpConfig struct {
	Delay time.Duration
	Times int
}

// HttpWorks fn返回错误时重试，一般用于对使用代理的网络请求的响应的处理，得到正确的结果后可通过stop=true提前结束
//
// httpConf.Delay 重试间隔 默认1秒
//
// httpConf.Times 重试次数 默认5次
func HttpWorks(fn func() (stop bool, err error), httpConf ...HttpConfig) (err error) {
	conf := HttpConfig{
		Delay: time.Second,
		Times: 5,
	}

	if len(httpConf) > 0 {
		c := httpConf[0]
		conf.Delay = c.Delay
		conf.Times = Nvl(c.Times, conf.Times)
	}

	var stop bool
	for i := 0; i < conf.Times; i++ {
		if stop, err = fn(); err == nil || stop {
			break
		}

		if conf.Delay > 0 {
			time.Sleep(conf.Delay)
		}
	}

	return err
}

// Http fn返回错误时重试，一般用于使用代理后的网络请求
//
// httpConf.Delay 重试间隔 默认1秒
//
// httpConf.Times 重试次数 默认5次
func Http[T any](fn func() (res T, err error), httpConf ...HttpConfig) (res T, err error) {
	conf := HttpConfig{
		Delay: time.Second,
		Times: 5,
	}

	if len(httpConf) > 0 {
		c := httpConf[0]
		conf.Delay = Nvl(c.Delay, conf.Delay)
		conf.Times = Nvl(c.Times, conf.Times)
	}

	for i := 0; i < conf.Times; i++ {
		res, err = fn()

		if err == nil {
			return res, err
		}

		if i >= conf.Times-1 {
			return res, NewErr("连接超时", err)
		}

		time.Sleep(conf.Delay)
	}

	return res, NewErr("连接超时", err)
}
